"""
主动服务管理器
统一管理主动服务的启动、停止和配置
"""

from typing import Dict, Any, Optional
import asyncio
import logging
from threading import Thread

from src.services.scheduled_proactive_service import ScheduledProactiveService
from src.utils.logging import get_logger

logger = get_logger(__name__)


class ProactiveServiceManager:
    """主动服务管理器"""
    
    _instance = None
    _initialized = False
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        if not self._initialized:
            self.scheduled_service = ScheduledProactiveService()
            self.scheduler_task: Optional[asyncio.Task] = None
            self.is_running = False
            self._initialized = True
    
    async def start_services(self):
        """
        启动主动服务
        """
        if self.is_running:
            logger.warning("主动服务已在运行中")
            return
        
        try:
            self.is_running = True
            logger.info("启动主动服务管理器")
            
            # 启动定时任务
            self.scheduler_task = asyncio.create_task(
                self.scheduled_service.start_scheduling()
            )
            
            logger.info("主动服务启动成功")
        except Exception as e:
            logger.error(f"启动主动服务失败: {e}")
            self.is_running = False
    
    async def stop_services(self):
        """
        停止主动服务
        """
        try:
            logger.info("停止主动服务管理器")
            
            # 停止定时任务
            self.scheduled_service.stop_scheduling()
            
            if self.scheduler_task:
                self.scheduler_task.cancel()
                try:
                    await self.scheduler_task
                except asyncio.CancelledError:
                    pass
            
            self.is_running = False
            logger.info("主动服务已停止")
        except Exception as e:
            logger.error(f"停止主动服务失败: {e}")
    
    def is_service_running(self) -> bool:
        """
        检查服务是否正在运行
        
        Returns:
            服务运行状态
        """
        return self.is_running
    
    async def reload_configuration(self, config: Dict[str, Any]):
        """
        重新加载配置
        
        Args:
            config: 新配置
        """
        try:
            logger.info("重新加载主动服务配置")
            # 这里可以实现配置重新加载逻辑
            # 暂时留空，作为扩展点
        except Exception as e:
            logger.error(f"重新加载配置失败: {e}")